<template>
  <div class="movie-clean">
    <!-- 控制面板 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>电影数据清洗</h3>
              <el-button-group>
                <el-button 
                  type="primary" 
                  :loading="cleaning"
                  @click="startClean"
                  :disabled="cleaning"
                >
                  <el-icon><Brush /></el-icon>
                  开始清洗
                </el-button>
                <el-button 
                  type="danger" 
                  @click="resetData"
                  :disabled="cleaning"
                >
                  <el-icon><RefreshRight /></el-icon>
                  重置数据
                </el-button>
              </el-button-group>
            </div>
          </template>
          
          <el-alert
            v-if="cleaning"
            type="info"
            :closable="false"
            show-icon
          >
            正在清洗数据，请稍候...
          </el-alert>
          
          <el-alert
            v-if="lastError"
            type="error"
            :closable="true"
            show-icon
            @close="lastError = ''"
            class="mt-3"
          >
            {{ lastError }}
          </el-alert>
        </el-card>
      </el-col>
    </el-row>

    <!-- 状态卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h4>清洗状态</h4>
            </div>
          </template>
          <div class="status-content">
            <el-tag :type="cleaning ? 'warning' : (processedCount > 0 ? 'success' : 'info')">
              {{ cleaning ? '清洗中' : (processedCount > 0 ? '已完成' : '未开始') }}
            </el-tag>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h4>处理数量</h4>
            </div>
          </template>
          <div class="status-content">
            <div class="number-display">
              <span class="count-number">{{ processedCount }}</span>
              <span class="count-unit">条</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h4>异常数据</h4>
            </div>
          </template>
          <div class="status-content">
            <div class="number-display">
              <span class="error-number">{{ errorCount }}</span>
              <span class="count-unit">条</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 日志面板 -->
    <el-card class="log-card">
      <template #header>
        <div class="card-header">
          <h4>清洗日志</h4>
          <el-button 
            type="primary" 
            link 
            @click="clearLogs"
            :disabled="!logs.length"
          >
            清空日志
          </el-button>
        </div>
      </template>
      <div class="log-content">
        <p 
          v-for="(log, index) in logs" 
          :key="index"
          :class="['log-item', `log-${log.type}`]"
        >
          <span class="log-time">{{ log.time }}</span>
          <span class="log-message">{{ log.message }}</span>
        </p>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.movie-clean {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 20px;
}

.mt-3 {
  margin-top: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.card-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.status-content {
  text-align: center;
  padding: 20px 0;
  min-height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.number-display {
  display: flex;
  align-items: baseline;
  justify-content: center;
}

.count-number {
  font-size: 36px;
  font-weight: bold;
  color: var(--el-color-primary);
  line-height: 1.2;
}

.error-number {
  font-size: 36px;
  font-weight: bold;
  color: var(--el-color-danger);
  line-height: 1.2;
}

.count-unit {
  margin-left: 8px;
  font-size: 16px;
  color: var(--el-text-color-secondary);
}

.log-card {
  margin-top: 20px;
}

.log-content {
  padding: 8px;
  font-size: 12px;
  line-height: 1.2;
}

.log-item {
  margin: 0;
  padding: 4px 0;
  border-bottom: 1px dashed var(--el-border-color-lighter);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.log-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.log-time {
  color: var(--el-text-color-secondary);
  margin-right: 8px;
  font-family: monospace;
}

.log-message {
  color: var(--el-text-color-regular);
}

.log-info {
  color: var(--el-text-color-regular);
}

.log-error {
  color: var(--el-color-danger);
}

.log-success {
  color: var(--el-color-success);
}
</style>

<script setup>
import { ref, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Brush, RefreshRight } from '@element-plus/icons-vue'
import { startClean as startCleanApi, resetClean as resetCleanApi, getCleanStatus } from '@/api/movie'

// 状态变量
const cleaning = ref(false)
const processedCount = ref(0)
const errorCount = ref(0)
const lastError = ref('')
const logs = ref([])

// 开始清洗
const startClean = async () => {
  try {
    cleaning.value = true
    processedCount.value = 0
    errorCount.value = 0
    lastError.value = ''
    
    const response = await startCleanApi()
    if (response?.status === 'success') {
      addLog('info', '开始清洗数据...')
      await pollCleanStatus()
    } else {
      throw new Error(response?.data?.message || '启动清洗失败')
    }
  } catch (error) {
    console.error('启动清洗失败:', error)
    lastError.value = error.message || '启动清洗失败'
    cleaning.value = false
    addLog('error', `启动失败: ${lastError.value}`)
    ElMessage.error(lastError.value)
  }
}

// 重置数据
const resetData = async () => {
  try {
    const response = await resetCleanApi()
    console.log('重置响应:', response)  // 添加调试日志
    
    if (response?.status === 'success' || response?.data?.status === 'success') {
      // 立即更新状态
      processedCount.value = 0
      errorCount.value = 0
      lastError.value = ''
      lastMessage = ''
      cleaning.value = false
      logs.value = []
      
      ElMessage.success('数据已重置')
      addLog('success', '数据已重置')
    } else {
      const errorMsg = response?.data?.message || '重置数据失败'
      console.error('重置失败:', errorMsg)
      throw new Error(errorMsg)
    }
  } catch (error) {
    console.error('重置数据失败:', error)
    lastError.value = error.message || '重置数据失败'
    addLog('error', `重置失败: ${lastError.value}`)
    ElMessage.error(lastError.value)
  }
}

// 轮询清洗状态
let statusTimer = null
const pollCleanStatus = async () => {
  if (statusTimer) {
    clearInterval(statusTimer)
  }
  
  const updateStatus = async () => {
    try {
      const response = await getCleanStatus()
      console.log('清洗状态:', response)
      
      if (response?.status === 'success') {
        const statusData = response.data || {}
        console.log('状态数据:', statusData)
        
        // 立即更新计数器
        processedCount.value = Number(statusData.processed_count || 0)
        errorCount.value = Number(statusData.error_count || 0)
        cleaning.value = Boolean(statusData.is_cleaning)
        
        // 更新消息
        if (statusData.message && statusData.message !== lastMessage) {
          addLog('info', statusData.message)
          lastMessage = statusData.message
        }
        
        // 处理错误
        if (statusData.error) {
          lastError.value = statusData.error
          addLog('error', statusData.error)
          clearInterval(statusTimer)
          cleaning.value = false
          return
        }
        
        // 检查清洗状态
        if (!statusData.is_cleaning) {
          clearInterval(statusTimer)
          cleaning.value = false
          
          if (!statusData.error && processedCount.value > 0) {
            const message = `清洗完成，共处理 ${processedCount.value} 条数据，错误 ${errorCount.value} 条`
            addLog('success', message)
            ElMessage.success(message)
          }
        }
      } else {
        throw new Error(response?.data?.message || '获取清洗状态失败')
      }
    } catch (error) {
      console.error('获取清洗状态失败:', error)
      clearInterval(statusTimer)
      lastError.value = error.message || '获取清洗状态失败'
      cleaning.value = false
      addLog('error', `状态获取失败: ${lastError.value}`)
      ElMessage.error(lastError.value)
    }
  }
  
  // 立即执行一次
  await updateStatus()
  // 然后每500ms执行一次，更频繁地更新状态
  statusTimer = setInterval(updateStatus, 500)
}

// 添加一个变量来跟踪最后一条消息，避免重复
let lastMessage = ''

// 添加日志
const addLog = (type, message) => {
  // 避免添加重复的日志
  if (logs.value.length > 0 && logs.value[0].message === message) {
    return
  }
  
  const now = new Date()
  const time = now.toLocaleTimeString()
  logs.value.unshift({ type, message, time })
  
  // 最多保留50条日志
  if (logs.value.length > 50) {
    logs.value = logs.value.slice(0, 50)
  }
}

// 清空日志
const clearLogs = () => {
  logs.value = []
}

// 组件销毁时清理定时器
onUnmounted(() => {
  if (statusTimer) {
    clearInterval(statusTimer)
  }
})
</script>